<template>
  <div ref="tableDiv" style="padding:0 10px;height: 100%">
    <!-- 搜索和新增区域 -->
    <div class="search-and-add">
      <!-- 每行三个搜索条件 -->
      <div class="search-line">
        <div class="search-item">
          <span class="search-item-text">客户代码：</span>
          <div class="search-item-put">
            <el-input v-model="customerCode" style="width:100%;border: none" placeholder="请输入客户代码" clearable></el-input>
          </div>
        </div>
        <div class="search-item">
          <span class="search-item-text">客户订单号：</span>
          <div class="search-item-put">
            <el-input v-model="customerDocNo" style="width:100%;border: none" placeholder="请输入客户订单号"
              clearable></el-input>
          </div>
        </div>
        <div class="search-item">
          <span class="search-item-text">工单号：</span>
          <div class="search-item-put">
            <el-input v-model="searchDocNo" style="width:100%;border: none" placeholder="请输入工单号" clearable></el-input>
          </div>
        </div>
        <div class="search-item">
          <span class="search-item-text">状态：</span>
          <div class="search-item-put">
            <el-select v-model="searchMoStatus" style="width: 100%" clearable placeholder="请选择状态">
              <el-option v-for="item in workOrderStatusList" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </div>

        </div>
      </div>
      <div style="display: flex ;width: 100%">
        <div class="search-line">
          <div class="search-item">
            <span class="search-item-text">品号：</span>
            <div class="search-item-put">
              <el-input v-model="searchItemCode" style="width:100%;border: none" placeholder="请输入品号"
                clearable></el-input>
            </div>
          </div>
          <div class="search-item">
            <span class="search-item-text">生产状态：</span>
            <div class="search-item-put">
              <el-select v-model="searchProduceStatus" clearable style="width: 100%" placeholder="请选择生产状态">
                <el-option v-for="status in ['待生产', '生产中', '已完成']" :key="status" :label="status" :value="status">
                </el-option>
              </el-select>
            </div>

          </div>
          <div class="search-item">
            <span class="search-item-text">车间：</span>
            <div class="search-item-put">
              <el-select v-model="searchWorkshopId" clearable style="width: 100%" placeholder="请选择车间"
                @change="handleSearchWorkshopChange">
                <el-option v-for="workshop in workshopList" :key="workshop.id" :label="workshop.workshopName"
                  :value="workshop.id">
                </el-option>
              </el-select>
            </div>
          </div>
          <div class="search-item">
            <span class="search-item-text">产线：</span>
            <div class="search-item-put">
              <el-select v-model="searchLineId" clearable style="width: 100%" placeholder="请选择产线"
                :disabled="!searchWorkshopId" :options="filteredLineList">
                <el-option v-for="line in filteredLineList" :key="line.id" :label="line.realityLineName"
                  :value="line.id">
                </el-option>
              </el-select>
            </div>
          </div>
        </div>
        <div class="button-line1">
          <el-button type="primary" @click="fetchTableData">查询</el-button>
        </div>
      </div>

    </div>

    <!--    :header-cell-style="{'text-align': 'center' }"-->
    <div class="table-wrapper">
      <!-- 按钮单独一行 -->
      <div class="button-line">
        <el-button type="primary" @click="addRow">新增排产</el-button>
        <!-- 新增取消排产按钮 -->
        <el-button type="danger" @click="confirmCancelProduction">取消排产</el-button>
      </div>
      <el-table ref="tableRef" v-loading="loading" :data="tableData" style="width: 100%;height: 88%;" class="table"
        :max-height="maxHeight" border :header-cell-style="headerCellStyle"
        :cell-style="{ padding: '0px', 'text-align': 'center' }" :row-class-name="tableRowClassName"
        :header-row-class-name="tableHeaderRowClassName" @mousedown="handleMouseDown" @mousemove="handleMouseMove"
        @mouseup="handleMouseUp" @mouseleave="handleMouseUp" @selection-change="handleSelectionChange">
        <!-- 新增复选框列 -->
        <el-table-column type="selection" width="40" fixed align="center" />
        <!-- 行号列 -->
        <el-table-column label="序号" width="40" fixed>
          <template #default="{ $index }">
            <!-- 考虑分页，计算实际行号 -->
            <span>{{ ($index + 1) + (page.currentPage - 1) * page.pageSize }}</span>
          </template>
        </el-table-column>
        <!-- 工单号列 -->
        <el-table-column prop="docNo" label="工单号" width="60" fixed>
          <!--          @click="handleEditClick(row, 'docNo','docNoInputRef')"-->
          <template #default="{ row }">
            <span v-if="!row.isNewRow && !row.editable.docNo">
              {{ row.docNo }}
            </span>
            <!--            <el-input
              v-else
              ref="docNoInputRef"
              v-model="row.docNo"
              style="width: 100%;border: none"
              @blur="handleDocNoBlur(row)"
            ></el-input>-->
            <el-select v-else ref="docNoInputRef" v-model="row.docNo" filterable remote reserve-keyword
              placeholder="请输入关键词" :remote-method="remoteMethod" :loading="docNoLoading">
              <el-option v-for="item in docNoList" :key="item.docNo" :label="item.docNo" :value="item.docNo"
                @click.native="handleDocNoBlur(row)">
              </el-option>
            </el-select>
          </template>
        </el-table-column>
        <!-- 客户PO列 -->
        <el-table-column prop="customerPO" label="PO" width="60" fixed>
          <template #default="{ row }">
            <span>{{ row.customerPO }}</span>
          </template>
        </el-table-column>
        <!-- 客户代码列 -->
        <el-table-column prop="customerCode" label="代码" width="60" fixed>
          <template #default="{ row }">
            <span>{{ row.customerCode }}</span>
          </template>
        </el-table-column>
        <!-- 客户订单号列 -->
        <el-table-column prop="customerDocNo" label="订单号" width="60" fixed>
          <template #default="{ row }">
            <span>{{ row.customerDocNo }}</span>
          </template>
        </el-table-column>
        <!-- 品号列 -->
        <el-table-column prop="itemCode" label="品号" width="60" fixed>
          <template #default="{ row }">
            <span>{{ row.itemCode }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="moStatus" label="状态" width="60" v-if="false" fixed>
          <template #default="{ row }">
            <span :style="{
              color:
                row.moStatus === '未生产' ? 'red' :
                  row.moStatus === '生产中' ? 'green' :
                    row.moStatus === '指定完工' ? 'orange' :
                      row.moStatus === '已完工' ? 'rgba(68,68,68,0.73)' :
                        row.moStatus === '已发料' ? 'rgba(221,31,132,0.73)' : 'black'
            }">
              {{ row.moStatus }}
            </span>

          </template>
        </el-table-column>
        <!-- 生产状态列 -->
        <el-table-column prop="produceStatus" label="生产状态" width="70" v-if="false" fixed>
          <template #default="{ row }">
            <span>{{ row.produceStatus }}</span>
          </template>
        </el-table-column>
        <!-- 车间列 -->
        <el-table-column prop="workshopName" label="车间" width="60" fixed>
          <template #default="{ row }">
            <span v-if="!row.isNewRow && !row.editable.workshopName" @click="handleWorkshopClick(row)">
              {{ row.workshopName }}
            </span>
            <el-select v-else v-model="row.workshopName" :style="{ borderColor: !row.workshopName ? 'red' : '' }"
              @change="(value) => filterLinesByWorkshop(row, true)">
              <el-option v-for="workshop in workshopList" :key="workshop.id" :label="workshop.workshopName"
                :value="workshop.workshopName" @click.native="row.workshopId = workshop.id"></el-option>
            </el-select>
          </template>
        </el-table-column>
        <!-- 产线列 -->
        <el-table-column prop="lineName" label="产线" width="60" fixed>
          <template #default="{ row }">
            <span v-if="!row.isNewRow && !row.editable.lineName" @click="handleLineClick(row)">{{ row.lineName }}</span>
            <el-select v-else v-model="row.lineName" :style="{ borderColor: !row.lineName ? 'red' : '' }"
              @change="handleLineChange(row)">
              <el-option v-for="line in getLineListByWorkshop(row)" :key="line.id" :label="line.realityLineName"
                :value="line.realityLineName" @click.native="row.lineId = line.id"></el-option>
            </el-select>
          </template>
        </el-table-column>
        <!-- 工单数量列 -->
        <el-table-column prop="completeQty" label="工单数" width="60" fixed>
          <template #default="{ row }">
            <span>{{ row.completeQty }}</span>
          </template>
        </el-table-column>

        <!-- 头数 -->
        <el-table-column prop="headCount" label="头数" width="60" v-if="false" fixed>
          <template #default="{ row }">
            <span v-if="!row.isNewRow && !row.editable.headCount" @click="handleHeadCountClick(row)"
              style="display: flex; width: 100%; height: 45px;justify-content: center;align-items: center">
              {{ row.headCount }}
            </span>
            <el-input-number v-else v-model="row.headCount" :min="0"
              style="width: 100%; padding: 0; margin: 0; border: none; box-sizing: border-box;" :controls="false"
              @blur="handleHeadCountBlur(row)"></el-input-number>
          </template>

        </el-table-column>

        <!-- 工单数量列 -->
        <el-table-column prop="remainingScheduleQty" label="剩余数" width="60" fixed>
          <template #default="{ row }">
            <span>{{ row.remainingScheduleQty }}</span>
          </template>
        </el-table-column>
        <!-- 完成数量列 -->
        <el-table-column prop="completedQty" label="完成数" width="60" fixed>
          <template #default="{ row }">
            <span>{{ row.completedQty }}</span>
          </template>
        </el-table-column>
        <!-- 计划数量列 -->
        <el-table-column prop="planQty" label="计划数" width="60" fixed>
          <template #default="{ row }">
            <span>{{ row.planQty }}</span>
          </template>
        </el-table-column>
        <!-- 日期列 -->
        <el-table-column v-for="(weekday, index) in weekdays" :key="index" :label="weekday" :width="60">
          <el-table-column :label="dateList[index].date" :width="60">
            <template #default="{ row, $index }">
              <span v-if="!row.isNewRow && !row.editable[dateList[index].date]"
                style="display: flex; width: 100%; height: 45px;justify-content: center;align-items: center"
                @click="handleEditClick(row, dateList[index].date, `dateInputRef_${index}_${$index}`)">
                {{ row[dateList[index].date] || '' }}
              </span>
              <el-input-number v-else :ref="`dateInputRef_${index}_${$index}`"
                v-model.number="row[dateList[index].date]" :min="0"
                style="width: 100%; padding: 0; margin: 0; border: none; box-sizing: border-box;" :controls="false"
                @input="calculatePlanQty(row)" @blur="handleInputBlur(row, dateList[index].date)"></el-input-number>
            </template>
          </el-table-column>
        </el-table-column>
      </el-table>
      <!-- 分页组件 -->
      <el-pagination style="float: right;" :current-page="page.currentPage" :page-sizes="[10, 20, 30]" :page-size="page.pageSize"
        layout="total, sizes, prev, pager, next, jumper" :total="page.total" @size-change="handleSizeChange"
        @current-change="handleCurrentChange">
      </el-pagination>

    </div>


  </div>
</template>
<script>
import moment from 'moment'
import { fetchList, addObj, putObj, delObj, getObj } from '@/api/workorder/workorderschedulemain'
import { getWorkshopList } from '@/api/pfoc/workshop' // 获取全部车间
import { getLineList } from '@/api/pfoc/realityproductlinemain' // 获取产线集合
import { getWorkOrderByDocNo, getDocNoList } from '@/api/workorder/workordercps'
import { remote } from "@/api/admin/dict"

export default {
  data() {
    return {
      page: {
        total: 0, // 总记录数
        currentPage: 1, // 当前页数
        pageSize: 20 // 每页显示多少条
      },
      customerCode: '',
      customerDocNo: '',
      searchDocNo: '',
      searchMoStatus: '',
      weekdays: [],
      dateList: [],
      tableData: [],
      currentDate: moment(),
      currentDateString: '',
      isDragging: false,
      startX: 0,
      scrollLeft: 0,
      currentDateIndex: 0,
      workshopList: [],
      loading: false,
      lineList: [],
      maxHeight: 0,
      permissions: {}, // 假设权限数据
      currentEditedDateField: null, // 新增属性，用于记录当前编辑的日期字段
      originalEditedValue: null, // 新增属性，用于记录当前编辑日期字段的原始值
      isEditingDateField: false, // 新增属性，用于标记是否正在编辑日期字段
      selectedRows: [],
      weekDayAndList: [], //存储几月几日以及对应的日期
      workOrderStatusList: [], //工单状态
      docNoList: [], //工单号集合
      docNoLoading: false,
      defaultProduceStatus: '待生产', // 新增的默认生产状态
      firstDay: '', // 新增的字段
      searchWorkshopId: '', //车间
      searchProduceStatus: '', //车间
      searchLineId: '', //产线'
      searchItemCode: '', //品号'
      filteredLineList: [] // 新增变量，用于存储过滤后的产线列表
    }
  },

  mounted() {
    this.initTableHeaders()
    this.fetchWorkshopAndLineList()
    this.fetchTableData() // 页面进入自动查询列表
    this.$nextTick(() => {
      this.maxHeight = this.$refs.tableDiv.offsetHeight - 100
      const el = document.createElement('div')
      if ('webkitOverflowScrolling' in el.style) {
        const tableWrapper = this.$refs.tableRef.$el.querySelector('.el-table__body-wrapper')
        if (tableWrapper) {
          tableWrapper.style.webkitOverflowScrolling = 'touch'
        }
      }
    })
    // 获取 app 元素
    const appElement = document.getElementById('app')
    if (appElement) {
      // 绑定 mouseup 事件
      appElement.addEventListener('mouseup', this.handleMouseUp)
    }
    // const appElement = document.getElementById('app')
    // appElement.addEventListener('mouseup', this.handleMouseUp)
  },

  beforeDestroy() {
    const appElement = document.getElementById('app')
    if (appElement) {
      // 移除 mouseup 事件
      appElement.removeEventListener('mouseup', this.handleMouseUp)
    }
    // appElement.removeEventListener('mouseup', this.handleMouseUp)
  },
  created() {
    //获取工单状态
    this.getWorkOrderStatus()
  },
  methods: {
    remoteMethod(query) {
      if (query !== '') {
        this.docNoLoading = true
        getDocNoList(query).then(response => {
          this.docNoList = response.data.data
          this.docNoLoading = false
        }).catch(() => {
          this.docNoLoading = false
          this.docNoList = []
        })
      } else {
        this.docNoList = []
      }
    },
    getWorkOrderStatus() {
      remote("workorder_status").then(response => {
        this.workOrderStatusList = response.data.data
      })
    },
    headerCellStyle({ row, column, rowIndex, columnIndex }) {
      if (columnIndex > 15 && rowIndex === 0) {
        if (column.label === '周六' || column.label === '周日') {
          return {
            'background-color': '#bcfa7a',
            'text-align': 'center',
            'color': 'rgba(0, 0, 0, .85)'
          }
        } else {
          return {
            'background-color': '#eca56b',
            'text-align': 'center',
            'color': 'rgba(0, 0, 0, .85)'
          }
        }
      }
      if (columnIndex > -1 && rowIndex === 1) {
        if (this.weekDayAndList.find(item => item.dateStr === column.label).weekDay === '周六' || this.weekDayAndList.find(item => item.dateStr === column.label).weekDay === '周日') {
          return {
            'background-color': '#bcfa7a',
            'text-align': 'center',
            'color': 'rgba(0, 0, 0, .85)'
          }
        } else {
          return {
            'background-color': '#eca56b',
            'text-align': 'center',
            'color': 'rgba(0, 0, 0, .85)'
          }
        }
      }
      return {
        'text-align': 'center',
        'color': 'rgba(0, 0, 0, .85)'
      }
    },
    // 初始化表格表头
    initTableHeaders() {
      const startDate = this.currentDate.clone().subtract(30, 'days')
      const weekDayAndList = []
      for (let i = 0; i < 61; i++) {
        const date = startDate.clone().add(i, 'days')
        const weekday = this.getWeekdayName(date)
        this.weekdays.push(weekday)
        this.dateList.push({
          date: date.format('YYYY-MM-DD')
        })
        weekDayAndList.push({
          weekDay: weekday,
          dateStr: date.format('YYYY-MM-DD')
        })
        if (date.isSame(this.currentDate, 'day')) {
          this.currentDateIndex = i
        }
      }
      this.weekDayAndList = weekDayAndList
      const index1 = this.dateList.findIndex(date => date.date === this.currentDate.format('YYYY-MM-DD'))
      this.scrollToColumn(index1)
    },

    // 滚动到指定列
    scrollToColumn(columnIndex) {
      const table = this.$refs.tableRef
      if (table) {
        table.doLayout()
        this.$nextTick(() => {
          const tableHeaderWrapper = table.$el.querySelector('.el-table__header-wrapper')
          const tableBodyWrapper = table.$el.querySelector('.el-table__body-wrapper')
          if (tableHeaderWrapper && tableBodyWrapper) {
            const columns = tableHeaderWrapper.querySelectorAll('th')
            if (columns && columns[columnIndex]) {
              const column = columns[columnIndex]
              let scrollLeft = column.offsetLeft
              // 增加 30px 的滚动距离
              scrollLeft -= 130

              tableHeaderWrapper.scrollTo({
                left: scrollLeft,
                behavior: 'smooth'
              })
              tableBodyWrapper.scrollTo({
                left: scrollLeft,
                behavior: 'smooth'
              })
              this.scrollPosition = scrollLeft
            }
          }
        })
      }
    },
    // 点击产线时的处理方法
    handleLineClick(row) {
      row.editable.lineName = true
      row.editable.workshopName = true // 使车间也变为可编辑状态
      const selectedWorkshop = this.workshopList.find(workshop => workshop.workshopName === row.workshopName)
      row.lineListByWorkshop = this.lineList.filter(line => line.workshopId === selectedWorkshop.id)
    },
    // 产线选择值改变时的处理方法
    handleLineChange(row) {
      console.log(row)
      this.saveRow(row).then(() => {
        row.editable.lineName = false
        row.editable.workshopName = false
      })
    },
    //头数点击处理
    handleHeadCountClick(row) {
      row.editable.headCount = true
    },
    // 头数离开处理
    handleHeadCountBlur(row) {
      this.saveRow(row).then(() => {
        row.editable.headCount = false
      })
    },
    handleSearchWorkshopChange() {
      const selectedWorkshop = this.workshopList.find(workshop => workshop.id === this.searchWorkshopId)
      if (selectedWorkshop) {
        this.filteredLineList = this.lineList.filter(line => line.workshopId === selectedWorkshop.id)
      } else {
        this.filteredLineList = []
      }
      this.searchLineId = '' // 清空产线选择
    },
    handleEditClick(row, field, inputRef) {
      row.editable[field] = true
      this.currentEditedDateField = field // 记录当前编辑的日期字段
      this.originalEditedValue = row[field] // 记录原始值
      this.isEditingDateField = this.dateList.some(date => date.date === field) // 判断是否为日期字段
      this.$nextTick(() => {
        const inputElement = this.$refs[inputRef]
        if (inputElement) {
          if (Array.isArray(inputElement)) {
            const input = inputElement[0].$el.querySelector('input')
            if (input) {
              input.focus()
            }
          } else {
            const input = inputElement.$el.querySelector('input')
            if (input) {
              input.focus()
            }
          }

        }
      })
    },

    // 点击车间时的处理方法
    handleWorkshopClick(row) {
      row.editable.workshopName = true
      row.editable.lineName = true // 使产线也变为可编辑状态
    },
    // 获取星期名称
    getWeekdayName(date) {
      const weekdayIndex = date.isoWeekday() - 1
      const chineseWeekdays = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
      return chineseWeekdays[weekdayIndex]
    },

    // 表格行样式
    tableRowClassName({ row, rowIndex }) {
      return ''
    },

    // 表格表头行样式
    tableHeaderRowClassName({ row, rowIndex }) {
      if (rowIndex === 0) {
        return 'main-header'
      } else if (rowIndex === 1) {
        return 'weekday-header'
      } else if (rowIndex === 2) {
        return 'date-header'
      } else if (rowIndex === 3) {
        return 'plan-quantity-header'
      }
      return ''
    },

    // 鼠标按下事件处理
    handleMouseDown(event) {
      this.isDragging = true
      this.startX = event.pageX
      const tableBodyWrapper = this.$refs.tableRef.$el.querySelector('.el-table__body-wrapper')
      if (tableBodyWrapper) {
        this.scrollLeft = tableBodyWrapper.scrollLeft
      }
    },

    // 鼠标移动事件处理
    handleMouseMove(event) {
      if (this.isDragging) {
        const deltaX = event.pageX - this.startX
        const tableBodyWrapper = this.$refs.tableRef.$el.querySelector('.el-table__body-wrapper')
        tableBodyWrapper.scrollLeft = this.scrollLeft - deltaX
      }
    },

    // 鼠标抬起事件处理
    handleMouseUp() {
      this.isDragging = false
    },

    // 查询数据
    fetchTableData() {
      this.loading = true
      const params = {}
      if (this.customerCode) {
        params.customerCode = this.customerCode
      }
      if (this.customerDocNo) {
        params.customerDocNo = this.customerDocNo
      }
      if (this.searchDocNo) {
        params.docNo = this.searchDocNo
      }
      if (this.searchMoStatus) {
        params.moStatus = this.searchMoStatus
      }
      if (this.searchProduceStatus) {
        params.produceStatus = this.searchProduceStatus
      }
      if (this.searchWorkshopId) { // 使用 searchWorkshopId
        params.workshopId = this.searchWorkshopId
      }
      if (this.searchLineId) { // 使用 searchLineId
        params.lineId = this.searchLineId
      }
      if (this.searchItemCode) { // 新增对品号的判断和添加
        params.itemCode = this.searchItemCode
      }
      const requestParams = Object.assign({
        current: this.page.currentPage,
        size: this.page.pageSize
      }, params)
      fetchList(requestParams)
        .then(response => {
          if (response.data.data && Array.isArray(response.data.data.records)) {
            const records = response.data.data.records
            this.tableData = records.map(record => {
              const newRow = { ...record }
              const scheduleDetails = record.workorderScheduleDetailsList
              this.dateList.forEach(date => {
                const detail = scheduleDetails.find(d => d.scheduleTime === date.date)
                newRow[date.date] = detail ? detail.planQty : 0
              })
              // 确保 lineName 被正确初始化
              const line = this.lineList.find(l => l.id === newRow.lineId)
              newRow.lineName = line ? line.realityLineName : ''
              // 初始化可编辑状态
              newRow.editable = {}
              Object.keys(newRow).forEach(key => {
                newRow.editable[key] = false
              })
              newRow.isNewRow = false
              // 处理从后台获取的 firstDay 字段
              newRow.firstDay = record.firstDay || ''
              return newRow
            })
          } else {
            console.error('返回数据格式错误，records 不是数组:', response.data.data.records)
            this.tableData = [] // 确保 tableData 始终是数组
          }
          this.loading = false
          this.page.total = response.data.data.total
        })
        .catch(error => {
          this.loading = false
          console.error('查询数据失败:', error)
        })
    },

    // 新增一行
    addRow() {
      const newRow = {
        id: '',
        docNo: '',
        customerPO: '',
        itemCode: '',
        produceStatus: this.defaultProduceStatus, // 将生产状态设置为待生产
        workshopId: '',
        workshopName: '',
        lineId: '',
        lineName: '',
        completeQty: '',
        headCount: 0,
        remainingScheduleQty: '',
        planQty: 0,
        editable: {},
        isNewRow: true,
        firstDay: '' // 初始化 firstDay 字段
      }
      this.dateList.forEach(date => {
        newRow[date.date] = 0
        newRow.editable[date.date] = false
      })
      Object.keys(newRow).forEach(key => {
        if (key !== 'editable') {
          newRow.editable[key] = false
        }
      })
      this.tableData.unshift(newRow)
    },

    // 工单号失去焦点处理
    handleDocNoBlur(row) {
      row.editable.docNo = false
      if (row.docNo) {
        getWorkOrderByDocNo(row.docNo)
          .then(response => {
            if (response.data.data) {
              row.customerPO = response.data.data.customerOrderNo
              row.moStatus = response.data.data.moStatus
              row.itemCode = response.data.data.itemCode
              row.customerCode = response.data.data.customerCode
              row.customerDocNo = response.data.data.salesOrderDocNo
              row.completedQty = Number(response.data.data.completedQty)
              row.completeQty = Number(response.data.data.planQty)
              row.remainingScheduleQty = Number(response.data.data.remainingScheduleQty)
              // 调用编辑接口
              this.saveRow(row)
            } else {
              this.$message.warning('未查询到当前工单数据')
            }
          })
          .catch(error => {
            console.error('查询数据失败:', error)
          })
      } else {
        this.$message.warning('工单号不能为空')
      }
    },

    // 输入框失去焦点处理
    handleInputBlur(row, field) {
      row.editable[field] = false
      this.updateFirstDay(row) // 调用更新 firstDay 的方法
      this.saveRow(row)
      this.currentEditedDateField = null // 输入框失去焦点时清空记录
      this.originalEditedValue = null // 清空原始值记录
    },
    // 新增方法，用于更新 firstDay 字段
    updateFirstDay(row) {
      let firstDateWithRecord = null
      this.dateList.forEach(date => {
        if (row[date.date] > 0 && !firstDateWithRecord) {
          firstDateWithRecord = date.date
        }
      })
      row.firstDay = firstDateWithRecord || ''
    },

    // 保存行数据
    saveRow(row) {
      return new Promise((resolve, reject) => {
        // 新增行验证
        if (row.isNewRow) {
          if (!row.docNo) {
            this.$message.warning('新增时工单号不能为空')
            return
          }
          if (!row.lineName) {
            this.$message.warning('新增时必须选择产线')
            return
          }
          let hasNonZeroValue = false
          this.dateList.forEach(date => {
            if (row[date.date] > 0) {
              hasNonZeroValue = true
            }
          })
          if (!hasNonZeroValue) {
            this.$message.warning('新增时至少要有一天排产')
            return
          }
        }

        // 非空验证
        if (!row.docNo) {
          this.$message.warning('工单号不能为空')
          return
        }
        if (!row.workshopName) {
          this.$message.warning('车间不能为空')
          return
        }
        if (!row.lineName) {
          this.$message.warning('产线不能为空')
          return
        }
        // 新增时验证工单号查询结果
        if (this.isNewRow(row)) {
          if (!row.itemCode || !row.completeQty) {
            this.$message.warning('请根据工单号查询出有效数据后再保存')
            return
          }
        }
        // 检查排产至少有一天数量不为 0
        let hasNonZeroQuantity = false
        this.dateList.forEach(date => {
          if (row[date.date] && row[date.date] > 0) {
            hasNonZeroQuantity = true
          }
        })
        if (!hasNonZeroQuantity) {
          this.$message.warning('排产至少有一天数量不为 0')
          return
        }

        // 仅在编辑日期字段时进行排产数量检查
        if (this.isEditingDateField) {
          // 检查当前编辑的日期列的值是否大于剩余数
          if (this.currentEditedDateField) {
            const availableQuantity = row.remainingScheduleQty + this.originalEditedValue
            if (row[this.currentEditedDateField] > availableQuantity) {
              this.$message.warning(`日期 ${this.currentEditedDateField} 的排产数量不能大于剩余排产数量`)
              row[this.currentEditedDateField] = this.originalEditedValue // 恢复到原始值
              this.calculatePlanQty(row)
              return
            }
          }
        }

        const isNewRow = !row.id // 假设新行没有id
        const api = isNewRow ? addObj : putObj
        row.workshopId = this.workshopList.find(w => w.workshopName === row.workshopName).id
        row.lineId = this.lineList.find(l => l.realityLineName === row.lineName).id
        // 构建符合要求的数据格式
        const newData = {
          id: row.id,
          docNo: row.docNo,
          itemCode: row.itemCode,
          workshopName: row.workshopName,
          workshopId: row.workshopId,
          lineName: row.lineName,
          produceStatus: row.produceStatus, // 添加生产状态字段
          lineId: row.lineId,
          completeQty: row.completeQty,
          headCount: row.headCount,
          remainingScheduleQty: row.remainingScheduleQty,
          planQty: row.planQty,
          firstDay: row.firstDay, // 添加 firstDay 字段
          workorderScheduleDetailsList: this.dateList.map(date => ({
            scheduleTime: date.date,
            planQty: row[date.date]
          }))
            .filter(item => item.planQty > 0) // 过滤掉计划数量为 0 的项
        }
        this.loading = true
        api(newData)
          .then((response) => {
            this.loading = false
            if (response && response.data.data) {
              // 如果返回的数据中有 id，将其赋给当前行
              row.id = response.data.data
              row.isNewRow = false // 标记为已有数据
              // 保存成功后，根据 id 查询最新数据
              this.fetchLatestRowData(row)
                .then(() => {
                  resolve()
                })
                .catch((getError) => {
                  reject(getError)
                })
            } else {
              resolve()
            }
          })
          .catch(error => {
            this.loading = false
            console.error('保存数据失败:', error)
            // 保存失败后调用查询最新数据方法
            this.fetchLatestRowData(row)
              .then(() => {
                reject(error)
              })
              .catch((getError) => {
                reject(getError)
              })
          })
      })
    },
    // 提取的查询最新数据方法
    fetchLatestRowData(row) {
      return new Promise((resolve, reject) => {
        getObj(row.id)
          .then((getResponse) => {
            if (getResponse && getResponse.data.data) {
              const newRowData = getResponse.data.data
              const scheduleDetails = newRowData.workorderScheduleDetailsList
              // 更新当前行的数据
              Object.assign(row, newRowData)
              this.dateList.forEach(date => {
                const detail = scheduleDetails.find(d => d.scheduleTime === date.date)
                row[date.date] = detail ? detail.planQty : 0
              })
              // 确保 lineName 被正确初始化
              const line = this.lineList.find(l => l.id === row.lineId)
              row.lineName = line ? line.realityLineName : ''
              // 更新相同工单号的数据行的剩余数量
              const updatedRemainingQty = newRowData.remainingScheduleQty
              this.tableData.forEach(item => {
                if (item.docNo === row.docNo) {
                  item.remainingScheduleQty = updatedRemainingQty
                }
              })
            }
            resolve()
          })
          .catch((getError) => {
            console.error('查询最新数据失败:', getError)
            reject(getError)
          })
      })
    },

    // 计算计划数量
    calculatePlanQty(row) {
      let total = 0
      // const backupRow = { ...row }
      this.dateList.forEach(date => {
        total += row[date.date] || 0
      })
      row.planQty = total
      this.updateFirstDay(row) // 调用更新 firstDay 的方法
    },

    // 获取车间和产线列表
    fetchWorkshopAndLineList() {
      Promise.all([
        getWorkshopList(),
        getLineList()
      ])
        .then(([workshopResponse, lineResponse]) => {
          this.workshopList = workshopResponse.data.data
          this.lineList = lineResponse.data.data
        })
        .catch(error => {
          console.error('获取车间和产线列表失败:', error)
        })
    },

    // 根据所选车间筛选产线
    filterLinesByWorkshop(row) {
      const selectedWorkshop = this.workshopList.find(workshop => workshop.workshopName === row.workshopName)
      if (selectedWorkshop) {
        row.lineListByWorkshop = this.lineList.filter(line => line.workshopId === selectedWorkshop.id)
      } else {
        row.lineListByWorkshop = []
      }
      row.lineName = '' // 清空产线选择
    },

    // 获取当前行的产线列表
    getLineListByWorkshop(row) {
      return row.lineListByWorkshop || []
    },
    // 新增处理选中行变化的方法
    handleSelectionChange(rows) {
      this.selectedRows = rows
    },
    // 新增取消排产确认方法
    confirmCancelProduction(row) {
      const docNos = this.selectedRows.map(row => row.docNo).join(', ')
      if (this.selectedRows.length > 0) {
        this.$confirm(`确定要取消以下工单号的排产吗？\n${docNos}`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          const ids = this.selectedRows
            .map(row => row.id)
            .filter(id => id !== null && id !== undefined && id !== '')
          console.log(ids)
          //去除所有空值
          console.log('取消排产的工单号:', ids)
          if (ids.length > 0) {
            this.deleteSelectedRows(ids)
          } else {
            this.tableData = this.tableData.filter(row => !this.selectedRows.includes(row))
            // 清空选中行
            this.selectedRows = []
          }
        }).catch(() => {
          // 用户取消操作
        })
      } else {
        this.$message.warning('请至少选择一行有效数据')
      }
    },
    // 新增删除选中行的方法
    deleteSelectedRows(ids) {
      this.loading = true
      delObj(ids)
        .then(() => {
          this.loading = false
          // 重新获取数据
          this.fetchTableData()
          // 清空选中行
          this.selectedRows = []
        })
        .catch(error => {
          this.loading = false
          console.error('删除数据失败:', error)
          this.$message.error('删除数据失败，请稍后重试')
        })
    },

    // 确认删除
    confirmDelete(row) {
      if (window.confirm('确定要删除这条记录吗？')) {
        delObj(row.id)
          .then(() => {
            const index = this.tableData.indexOf(row)
            if (index > -1) {
              this.tableData.splice(index, 1)
            }
            // 重新调用查询接口
            this.fetchTableData()
          })
          .catch(error => {
            console.error('删除数据失败:', error)
          })
      }
    },

    // 每页显示数量变化时触发
    handleSizeChange(newSize) {
      this.page.pageSize = newSize
      this.fetchTableData()
    },

    // 当前页码变化时触发
    handleCurrentChange(newPage) {
      this.page.currentPage = newPage
      this.fetchTableData()
    },

    // 判断是否为新增行
    isNewRow(row) {
      return !row.id // 假设新行没有id
    }
  }
}
</script>

<style scoped>
.table-wrapper {
  width: auto;
  overflow: hidden;
  overflow-x: auto;
  background: #fff;
  box-sizing: border-box;
  padding: 10px;
  height: 86%;
}

.table-wrapper-inner {
  width: 100%;
  height: 100%;
  overflow-x: auto;
  margin-left: -15px;
  padding-left: 15px;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}

.el-table th,
.el-table td {
  border: 1px solid #ccc;
  padding: 0px;
  text-align: center;
  white-space: nowrap;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}

.el-table th {
  width: 120px;
}

.el-table {
  border-collapse: collapse;
  width: auto;
  table-layout: fixed;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}

.main-header {
  border-top: 2px solid #000;
  border-bottom: 2px solid #000;
}

.weekday-header {
  border-bottom: 1px solid #ccc;
}

.date-header {
  border-bottom: 1px solid #ccc;
}

.plan-quantity-header {
  border-bottom: 1px solid #ccc;
}

.work-order-header {
  height: 120px;
  vertical-align: middle;
  position: sticky;
  left: 0;
  background-color: white;
  z-index: 1;
  outline: 1px solid #ccc;
}

.table-cell {
  border-bottom: 1px solid #ccc;
}

.table-wrapper-inner::-webkit-scrollbar {
  display: none;
}

.table-wrapper-inner {
  -ms-overflow-style: none;
  scrollbar-width: none;
}

.search-and-add {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  height: auto;
  margin-bottom: 10px;
  background: #fff;

}

.search-line {
  width: 80%;
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  margin-top: 10px;
}

.search-item {
  flex: 1;
  display: flex;
}

.search-item-text {
  width: 100px;
  display: flex;
  padding: 0 0 0 20px;
  font-size: 14px;
  color: #606266;
}

.search-item-put {
  flex: 1;
}

.button-line1 {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  margin-left: 30px;
}

.button-line {
  display: flex;
  align-items: center;
  width: 100%;
  justify-content: flex-start;
  margin: 0 0 10px;
}

.el-input {
  width: 200px;
  margin-right: 15px;
  border: 1px solid #ccc;
  border-radius: 5px;
  padding: 0px;
}

.el-input::placeholder {
  color: #999;
}

.el-button {
  border: none;
  border-radius: 5px;
  padding: 8px 15px;
  font-size: 14px;
  cursor: pointer;
  background-color: #409EFF;
  color: white;
}

.el-button:hover {
  background-color: #2d8cf0;
}

/deep/ .el-input-number__inner {
  padding: 0;
}

/deep/ .el-table .cell {
  padding: 0;
}

.el-input-number.is-without-controls /deep/ .el-input__inner {
  padding: 0;
}

.table:hover {
  cursor: pointer;
}

/deep/ .el-select .el-input--suffix .el-input__inner {
  padding-right: 15px !important;
}
</style>
